package com.cgly.medical.security;

import com.cgly.medical.entity.AccountModel;
import com.cgly.medical.service.impl.UserDetailsServiceImpl;
import com.cgly.medical.util.MD5Utils;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @program: CGLY
 * @description:
 * @author: chen di
 * @create: 2022-08-26 10:27
 */
@Component
public class MyAuthenticationProvider implements AuthenticationProvider {

    @Resource
    UserDetailsServiceImpl myUserService;

    //用户名、密码真正判断的地方
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        System.out.println("开始身份认证");
        String username = authentication.getName();
        String password = (String) authentication.getCredentials();
        AccountModel user = myUserService.loadUserByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("账号不存在!");
        }
        password = MD5Utils.md5(password + user.getSalt());
        if (!user.getPassword().equals(password)) {

            throw new BadCredentialsException("密码不正确!");
        }
        // principal: 主要信息; credentials: 证书; authorities: 权限;
        System.out.println("认证成功");

        return authentication;
//                        return new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities());

    }

    @Override
    public boolean supports(Class<?> authentication) {
//         UsernamePasswordAuthenticationToken: Authentication接口的常用的实现类.
                        return UsernamePasswordAuthenticationToken.class.equals(authentication);
    }
}